<template>
  <!-- 自助优惠券核销二维码 -->
  <div>
    <div style="text-align: center; position: relative" :id="`couponQr${type}`">
      <div class="title">
        <span>{{ name }}自助核销码</span>
      </div>
      <vue-qr
        :text="scanText"
        :margin="20"
        :size="200"
        class="d-block mx-auto"
      />
      <slot></slot>
    </div>
    <el-button type="primary" @click="downloadImg()">导出核销码</el-button>
  </div>
</template>

<script>
import { scrollTo } from "@/utils/scroll-to";
import vueQr from "vue-qr";
import html2canvas from "html2canvas";

export default {
  name: "QrCode",
  props: {
    type: {
      type: String,
      required: true,
    },
    name: {
      type: String,
      required: true,
    },
    url: {
      type: String,
      required: true,
    },
  },
  components: {
    vueQr,
  },
  data() {
    return {
      scanText: "",
    };
  },
  watch: {
    url: {
      handler() {
        this.scanText = this.url + this.type;
        console.log(`${this.name}优惠券url：`, this.scanText);
      },
      immediate: true,
    },
  },

  methods: {
    downloadImg() {
      try {
        window.pageYoffset = 0;
        document.documentElement.scrollTop = 0;
        document.body.scrollTop = 0;
        let id = "couponQr" + this.type;
        html2canvas(document.getElementById(id), {
          allowTaint: false,
        }).then((canvas) => {
          const a = document.createElement("a");
          const event = new MouseEvent("click");
          a.download = this.name;
          a.href = canvas.toDataURL("image/jpeg");
          a.dispatchEvent(event);
          this.$emit("downloadImg");
        });
      } catch (error) {
        this.msgError("导出二维码失败，请刷新重试~");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
#couponQr1,
#couponQr2,
#couponQr3,
#couponQr4,
#couponQr100 {
  padding-bottom: 20px;
  img {
    border: 1px solid #ddd;
    padding: 10px;
    cursor: pointer;
  }
}
.title {
  font-size: 18px;
  color: #000;
  padding: 20px 0;
  text-align: center;
  font-weight: 600;
  span {
    display: inline-block;
    letter-spacing: 3px;
  }
  img {
    border: 1px solid;
  }
}
</style>
